/**
 * Created by zhaojiuyang1 on 15/7/8.
 */
var gpio = require("pi-gpio");
var Q = require("q");
var moment = require("moment");
var _ = require("underscore");
var emitter = require('./emitter');

var outputGpio = 7;
var inputGpio = 11;
gpio.open(outputGpio,"out",function(err){
    if(err){
        gpio.open(inputGpio,"in",function(err){
            if(err){
                emitter.emit("ready");
            }
        })
    }
});
var output7 = function(value){
    var deferred = Q.defer();
    gpio.write(outputGpio,value,function(err){
        if(!_.isNull(err)) return deferred.reject(err);
        deferred.resolve();
    });
    return deferred.promise;
};
function autoSend(){
    output7(1)
        .then(function(){
            console.log("send out 1 on 7");
            setTimeout(function(){
                console.log("send out 0 on 7");
                output7(0).then(function(){
                    setTimeout(function(){
                        autoSend();
                    },10000);
                    emitter.emit("hasSend");
                })
            },0.01);
        });
}
emitter.on("ready",function(){
    autoSend();
});

emitter.on("hasSend",function(){
    var timeStart = 0;
    var timeEnd = 0;
    function getValue(){
        getValue11.then(function(value){
            if(value == 1 && timeStart === 0){
                timeStart = new Date().getTime();
            }
            if(value === 0 && timeEnd === 0 && timeStart!=0){
                timeEnd = new Date().getTime();
            }
            if(timeStart != 0 && timeEnd != 0){
                return timeEnd - timeStart;
            }else{
                getValue();
            }
        })
    }
    var len = getValue();
    var pathLen = 340 * (len / 1000);
    console.log("distance is : %s",pathLen);
});

emitter.on("error",function(){
    gpio.close(7);
    gpio.close(11);
});